package org.jeecg.modules.demo.qingjia.controller;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.mapper.LwgyBaseBedMapper;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.mapper.LwgyBaseStudentMapper;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.demo.qingjia.entity.LwgyQingJia;
import org.jeecg.modules.demo.qingjia.mapper.LwgyQingJiaMapper;
import org.jeecg.modules.demo.qingjia.service.ILwgyQingJiaService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 请假表
 * @Author: jeecg-boot
 * @Date:   2023-05-08
 * @Version: V1.0
 */
@Api(tags="请假表")
@RestController
@RequestMapping("/qingjia/lwgyQingJia")
@Slf4j
public class LwgyQingJiaController extends JeecgController<LwgyQingJia, ILwgyQingJiaService> {
	@Autowired
	private ILwgyQingJiaService lwgyQingJiaService;

	 @Autowired
	 private ISysBaseAPI sysBaseAPI;
	 @Autowired
	 private ILwgyBaseStudentService lwgyBaseStudentService;

	 @Resource
	 private LwgyBaseStudentMapper lwgyBaseStudentMapper;

	 @Resource
	 private LwgyBaseBedMapper lwgyBaseBedMapper;

	 @Resource
	 private LwgyQingJiaMapper lwgyQingJiaMapper;

	
	/**
	 * 分页列表查询
	 *
	 * @param lwgyQingJia
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "请假表-分页列表查询")
	@ApiOperation(value="请假表-分页列表查询", notes="请假表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<LwgyQingJia>> queryPageList(LwgyQingJia lwgyQingJia,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		/*QueryWrapper<LwgyQingJia> queryWrapper = QueryGenerator.initQueryWrapper(lwgyQingJia, req.getParameterMap());
		Page<LwgyQingJia> page = new Page<LwgyQingJia>(pageNo, pageSize);
		IPage<LwgyQingJia> pageList = lwgyQingJiaService.page(page, queryWrapper);
		return Result.OK(pageList);*/
		QueryWrapper<LwgyQingJia> queryWrapper = QueryGenerator.initQueryWrapper(lwgyQingJia, req.getParameterMap());
		Page<LwgyQingJia> page = new Page<>(pageNo, pageSize);
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		List<String> roles = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
		//管理员不限制
		//辅导员只看他自己学生申请
		//学生只看他提交的
		List<Map<String,String>> fdyList = null;
		if(roles.contains("fdy")){
			List<String> classId = lwgyBaseStudentService.getClassIdBySysUser(sysUser);
			if (oConvertUtils.listIsNotEmpty((classId))) {
				queryWrapper.in("student_class", classId);
			} else {
				queryWrapper.eq("student_class", "null");
			}
			/*		queryWrapper.in("admin_id",sysUser.getWorkNo());*/
		}else if(roles.contains("user_students")){
			queryWrapper.eq("student_number",sysUser.getWorkNo());
		}

		IPage<LwgyQingJia> pageList = lwgyQingJiaService.page(page, queryWrapper);

		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param lwgyQingJia
	 * @return
	 */
	@AutoLog(value = "请假表-添加")
	@ApiOperation(value="请假表-添加", notes="请假表-添加")
	//@RequiresPermissions("qingjia:lwgy_qingjia:add")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody LwgyQingJia lwgyQingJia) {
		/*lwgyQingJiaService.save(lwgyQingJia);
		return Result.OK("添加成功！");*/
		LwgyBaseStudent lwgyBaseStudent =lwgyBaseStudentMapper.getStudentByNumber(lwgyQingJia.getStudentNumber());

		if(oConvertUtils.isNotEmpty(lwgyBaseStudent)){
			lwgyQingJia.setStudentId(lwgyBaseStudent.getId());
			lwgyQingJia.setStudentCampus(lwgyBaseStudent.getStudentCampus());
			lwgyQingJia.setStudentCollege(lwgyBaseStudent.getStudentCollege());
			lwgyQingJia.setStudentMajor(lwgyBaseStudent.getStudentMajor());
			lwgyQingJia.setStudentYear(lwgyBaseStudent.getStudentYear());
			lwgyQingJia.setStudentClass(lwgyBaseStudent.getStudentClass());
			lwgyQingJia.setRoomSex(lwgyBaseStudent.getStudentSex());
		}
		LwgyBaseBed lwgyBaseBed = lwgyBaseBedMapper.getBedByStuId(lwgyBaseStudent.getId());
		if(oConvertUtils.isNotEmpty(lwgyBaseBed)){
			lwgyQingJia.setBuildingId(lwgyBaseBed.getBuildingId());
			lwgyQingJia.setUnitId(lwgyBaseBed.getUnitId());
			lwgyQingJia.setLayerId(lwgyBaseBed.getLayerId());
			lwgyQingJia.setRoomId(lwgyBaseBed.getRoomId());
		}
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String leaveMethod = lwgyQingJia.getLeaveMethod();
		String content="";
		if(oConvertUtils.isNotEmpty(leaveMethod) && "0".equals(leaveMethod)) {//当天21时就能回来的无需审核直接通过
			lwgyQingJia.setProcessingState("1");
			content = "管理员同意你的请假申请";
			String username = sysUser.getUsername();
			String stuUsername = oConvertUtils.isEmpty(lwgyQingJia.getFromUser()) ? "admin":lwgyQingJia.getFromUser();
			sysBaseAPI.sendSysAnnouncement(new MessageDTO(username, stuUsername, "申请回执", "管理员你的申请：原因如下->" + lwgyQingJia.getRefuseReason(), "1"));
			sendSysToAdmin(lwgyQingJia,"请假","",username,stuUsername);
			lwgyQingJia.setProcessingState("1");
			lwgyQingJia.setProcessingResult("1");
		}else if(oConvertUtils.isNotEmpty(leaveMethod) && "1".equals(leaveMethod)) {
			lwgyQingJia.setProcessingState("0");
		}else{
			lwgyQingJia.setProcessingState("0");
		}
		String username = sysUser.getUsername();
		lwgyQingJia.setFromUser(username);
		lwgyQingJia.setDelFlag("0");
		lwgyQingJia.setQingState("0");
		List<LwgyQingJia> list = lwgyQingJiaMapper.findByNumber(lwgyQingJia.getStudentNumber());
		if (list.size() > 0) {
			return Result.error("该学生的请假申请正在审核或待销假，不能重复的申请！！");
		}
		lwgyQingJia.setRefuseReason(content);
		lwgyQingJiaService.save(lwgyQingJia);
		return Result.OK("申请成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param lwgyQingJia
	 * @return
	 */
	/*@AutoLog(value = "请假表-编辑")
	@ApiOperation(value="请假表-编辑", notes="请假表-编辑")
	//@RequiresPermissions("qingjia:lwgy_qingjia:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody LwgyQingJia lwgyQingJia) {
		lwgyQingJiaService.updateById(lwgyQingJia);
		return Result.OK("编辑成功!");
	}*/
	 /**
	  *  编辑
	  *
	  * @param
	  * @return
	  */
	@AutoLog(value = "请假申请-编辑")
	 @ApiOperation(value="请假申请-编辑", notes="请假申请-编辑")
	 @PutMapping(value = "/edit")
	 public Result<?> edit(@RequestBody LwgyQingJia lwgyQingJia) {
		 String processingResult = lwgyQingJia.getProcessingResult();
		 System.out.println("988888:"+processingResult);
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String username = sysUser.getUsername();
		 String stuUsername = oConvertUtils.isEmpty(lwgyQingJia.getFromUser()) ? "admin":lwgyQingJia.getFromUser();
		  String content = "";
		  String qingState=lwgyQingJia.getQingState();
		  String xjCause=lwgyQingJia.getXjCause();
		  if("0".equals(qingState)){
			  return Result.error("不能选择待销假!!!!");
		  }
		  if(oConvertUtils.isNotEmpty(qingState)&&"1".equals(qingState)){
		  	lwgyQingJia.setQingState(qingState);
		  	lwgyQingJia.setXjCause(xjCause);
		  	lwgyQingJia.setXjTime(new Date());
		  }
		 if(oConvertUtils.isNotEmpty(processingResult) && "0".equals(processingResult)) {
			 content = "管理员拒绝你的请假申请";
			 sysBaseAPI.sendSysAnnouncement(new MessageDTO(username, stuUsername, "申请回执", "管理员拒绝了你的申请：原因如下->" + lwgyQingJia.getRefuseReason(), "1"));
			 sendSysToAdmin(lwgyQingJia,"请假","",username,stuUsername);
			 lwgyQingJia.setXjTime(new Date());
			 lwgyQingJia.setQingState("1");
		 }else if("1".equals(processingResult)){//同意
			 content = "管理员同意你的请假申请";
			 sysBaseAPI.sendSysAnnouncement(new MessageDTO(username, stuUsername, "申请回执", "管理员你的申请：原因如下->" + lwgyQingJia.getRefuseReason(), "1"));
			 sendSysToAdmin(lwgyQingJia,"请假","",username,stuUsername);
			 }
		    lwgyQingJia.setRefuseReason(content);
			lwgyQingJiaService.updateById(lwgyQingJia);
			return Result.OK("编辑成功!");
		 }



	 public void sendSysToAdmin(LwgyQingJia lwgyQingJia ,String  type,String bedCode,String username,String stuUsername){
		 String content="";
		 if(type.equals("请假")) {
			 content = "已同意学生" + username + "的" + type + "申请.";
		 }
		 sysBaseAPI.sendSysAnnouncement(new MessageDTO("admin",stuUsername,"请销假申请操作通知",content,"1"));

	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "请假表-通过id删除")
	@ApiOperation(value="请假表-通过id删除", notes="请假表-通过id删除")
	//@RequiresPermissions("qingjia:lwgy_qingjia:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		lwgyQingJiaService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "请假表-批量删除")
	@ApiOperation(value="请假表-批量删除", notes="请假表-批量删除")
	//@RequiresPermissions("qingjia:lwgy_qingjia:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.lwgyQingJiaService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "请假表-通过id查询")
	@ApiOperation(value="请假表-通过id查询", notes="请假表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		LwgyQingJia lwgyQingJia = lwgyQingJiaService.getById(id);
		if(lwgyQingJia==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(lwgyQingJia);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param lwgyQingJia
    */
    //@RequiresPermissions("qingjia:lwgy_qingjia:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LwgyQingJia lwgyQingJia) {
        return super.exportXls(request, lwgyQingJia, LwgyQingJia.class, "请假表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("qingjia:lwgy_qingjia:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LwgyQingJia.class);
    }

}
